package net.xdclass.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.OSSConfig;
import net.xdclass.util.CommonUtil;
import net.xdclass.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadUserImg(MultipartFile file) {

        //获取相关配置
        String bucketName = ossConfig.getBucketname();
        String endPoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        //获取原生文件名
        String orginalFileName = file.getOriginalFilename();

        //jdk8日期格式
        LocalDateTime ldt = LocalDateTime.now();
        DateTimeFormatter dtf =  DateTimeFormatter.ofPattern("yyyy/MM/dd");

        //拼装路径，oss上存储的路径 2021//11/18/dsafio2.jpg
        String folder = dtf.format(ldt);
        String fileName = CommonUtil.generateUUID();
        String extension = orginalFileName.substring(orginalFileName.lastIndexOf("."));

        //在oss创建文件夹
        String newFileName = "user/" +folder +"/" +fileName + extension;

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, newFileName, file.getInputStream());
            //拼装返回路径
            if (putObjectResult != null){
                String imgUrl = "https://" + bucketName + "." + endPoint +"/" +newFileName;
                return imgUrl;
            }
        } catch (IOException e) {
            log.error("文件上传失败:{}",e);
        }finally {
            //关闭oss服务
            ossClient.shutdown();
        }

        return null;
    }
}
